<?php

namespace App\Http\Controllers\Purchase;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Chanjet\TplusCommonController;
use App\Http\Validate\Order\Salesorder;
use App\Http\Validate\Purchase\PurchaseOrder as PurchasePurchaseOrder;
use App\Models\Balance\Balance;
use App\Models\Common\EditLog;
use App\Models\Custom\Custom;
use App\Models\Fee\FeeType;
use App\Models\Manger\Manger;
use App\Models\Order\Saleimplementation;
use App\Models\Order\Saleimplementationsub;
use App\Models\Order\Saleorder;
use App\Models\Order\Saleordersub;
use App\Models\Order\Saleordersub as ModelSaleordersub;
use App\Models\Purchase\PurchaseAgreement;
use App\Models\Purchase\PurchaseOrder;
use App\Models\Purchase\PurchaseOrderOtherfee;
use App\Models\Purchase\PurchaseOrderProcess;
use App\Models\Purchase\PurchaseOrderProcessSub;
use App\Models\Purchase\PurchaseOrderSub;
use App\Models\Purchase\PurchasePayOrderApprove;
use App\Models\Purchase\PurchasePayOrderNew;
use App\Models\Purchase\PurchasePrePayOrder;
use App\Models\Purchase\PurchaseStockinOrder;
use App\Models\Purchase\PurchaseStockinOrderSub;
use App\Models\Purchase\PurchaseWarehousingOrderwithpay;
use App\Models\Settle\SettleCompany;
use App\Models\Settle\SettleType;
use App\Models\Steel\SteelArchive;
use App\Models\Stock\Stock;
use App\Models\Warehouse\WarehouseList;
use App\Services\Chanjet\ChanjetRequest;
use App\Services\Common\SnCode;
use App\Services\Common\TableExtFeild;
use App\Services\Purchase\PurchaseCommon;
use App\Services\Stock\Stock as StockStock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Order\SaleorderController;
use App\Models\Order\Saleorder as ModelSaleorder;
/**
 * 采购订单相关
 */
class PurchaseOrderController extends BaseController
{
    /**
     * 获取表头
     *
     * @param Request $request
     * @return void
     */
    public function gettablefield()
    {
        $cpid = $this->mangerinfo['cpid'];
        $mainextfield = TableExtFeild::getFeildTitle((new PurchaseOrder())->getTable(), $cpid);
        $subextfield = TableExtFeild::getFeildTitle((new PurchaseOrderSub())->getTable(), $cpid);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['mainextfield' => $mainextfield, 'subextfield' => $subextfield]]);
    }
    /**
     * 新增采购订单
     * 结算模式为：锁价/点价/后结算，
     * 锁价后单价不进行修改，锁单价（基价+加价）在当天
     * 选择点价，增加时间，添加时间（精确到天）
     * 后结算采购**订单付款按钮置灰**，后续流程中的单价只有后结算模式可修改，其他模式不变
     * 定尺输入件数，自动计算单重、重量、金额；
     * 过磅输入件数、重量，自动计算单重、价格；
     * 理计输入件数，单重取库存平均单重，自动计算重量、金额--初始输入重量和件数，自动计算单重和价格
     */
    public function dopostadd(Request $request)
    {

        $req_data = $request->only([
            'pa_id',
            'order_date',
            'remark',
            'suborder',
            'otherfee',
            'pa_type',
            'custom_id',
            'pa_settle_company_id',
            'sales_manger_id',
            'settle_model',
            'invoice_type',
            'settle_model_start_time',
            'settle_model_end_time',
            'field_1',
            'field_2',
            'field_3',
            'field_4',
            'field_5',
            'field_6',
            'field_7',
            'field_8',
            'field_9',
            'field_10'
        ]);
        $suborder = is_array($req_data['suborder']) ? $req_data['suborder'] : (is_array(json_decode($req_data['suborder'], true)) ? json_decode($req_data['suborder'], true) : []);
        if (count($suborder) <= 0) {
            return response()->json(['code' => '001', 'msg' => '订单数据不能为空']);
        }

        // $otherfee = is_array($req_data['otherfee']) ? $req_data['otherfee'] : (is_array(json_decode($req_data['otherfee'], true)) ? json_decode($req_data['otherfee'], true) : []);
        $otherfee = [];
        $cpid = $this->mangerinfo['cpid'];

        if (intval($req_data['pa_id']) > 0) { //选择协议
            $Validate = new PurchasePurchaseOrder();
            if (!$Validate->check($req_data)) { //初筛过滤
                return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
            }

            $painfo = PurchaseAgreement::with([
                'mangerinfo' => function ($query) {
                    $query->select(['id', 'realname', 'username']);
                },
                'custominfo' => function ($query) {
                    $query->select(['id', 'company_name']);
                },
                'settlecompany' => function ($query) {
                    $query->select(['id', 'settle_no', 'settle_company_name']);
                },

            ])->where([['id', $req_data['pa_id']], ['cpid', $cpid]])->first();
            if (!$painfo) {
                return response()->json(['code' => '001', 'msg' => '无效合同信息']);
            }
            $painfo = $painfo->toArray();

            if ($painfo['type'] == 4) {
                return response()->json(['code' => '001', 'msg' => '业务自采不可手动新增']);
            }


            $maindata = [
                'cpid' => $cpid,
                'manger_id' => $this->mangerinfo['id'],
                'pa_id' => $painfo['id'],
                'pa_type' => $painfo['type'],
                'custom_id' => $painfo['custom_id'],
                'company_name' => $painfo['custominfo']['company_name'],
                'pa_contract_no' => $painfo['contract_no'],
                'pa_sn_code' => $painfo['sn_code'],
                'order_sn_code' => SnCode::getSnCode('PO_'),
                'sales_manger_id' => $painfo['sales_manger_id'],
                'sales_manger_name' => isset($painfo['mangerinfo']['realname']) ? $painfo['mangerinfo']['realname'] : '',
                'order_date' => strtotime($req_data['order_date']),
                'invoice_type' => $painfo['invoice_type'],
                'settle_model' => $painfo['settle_model'],
                'remark' => isset($req_data['remark']) ? $req_data['remark'] : '',
                'pa_settle_company_id' => $painfo['settlecompany']['id'],
                'pa_settle_company_name' => $painfo['settlecompany']['settle_company_name'],
                'settle_model_start_time' => $painfo['settle_model_start_time'] ?? 0,
                'settle_model_end_time' => $painfo['settle_model_end_time'] ?? 0,
                'is_band' => 1,
                'create_at' => time(),
                'update_at' => time(),
                'create_manger_id' => $this->mangerinfo['id'],
            ];
        } else { //未选择协议
            $Validate = new PurchasePurchaseOrder('addbyform');
            if (!$Validate->check($req_data)) { //初筛过滤
                return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
            }


            $pa_type = $req_data['pa_type'];

            if ($pa_type == 4) {
                return response()->json(['code' => '001', 'msg' => '业务自采不可手动新增']);
            }

            $settle_model_end_time = isset($req_data['settle_model_end_time']) ? ((strtotime($req_data['settle_model_end_time']) > 0) ? strtotime($req_data['settle_model_end_time']) : intval($req_data['settle_model_end_time'])) : 0;
            $settle_model_start_time = isset($req_data['settle_model_start_time']) ? ((strtotime($req_data['settle_model_start_time']) > 0) ? strtotime($req_data['settle_model_start_time']) : intval($req_data['settle_model_start_time'])) : 0;

            if ($pa_type == 3 || $pa_type == 4) {
                if (!in_array($req_data['settle_model'], [1, 2])) {
                    return response()->json(['code' => '001', 'msg' => '只支持点价、锁价']);
                }
            } else {
                if (!in_array($req_data['settle_model'], [1, 3])) {
                    return response()->json(['code' => '001', 'msg' => '只支持锁价、后结算']);
                }
            }

            if ($req_data['settle_model'] == 1) {
                $req_data['settle_model_start_time'] = 0;
                $req_data['settle_model_end_time'] = time();
            }

            if ($req_data['settle_model'] == 2) {

                $req_data['settle_model_start_time'] = 0;
                if ($settle_model_end_time > time()) {
                    $req_data['settle_model_end_time'] = $settle_model_end_time;
                } else {
                    return response()->json(['code' => '001', 'msg' => '点价模式日期需大于当前时间']);
                }
            }

            if ($req_data['settle_model'] == 3) {
                //后结算模式
                // 2025-10-18修改为非必填 修改需求；如果不填写 绑定合同的时候获取合同的时间
//                if ($req_data['settle_model_start_time'] < 0 || $req_data['settle_model_end_time'] < 0) {
//                    return response()->json(['code' => '001', 'msg' => '后结算模式需选择时间范围']);
//                }
                $req_data['settle_model_end_time'] = $settle_model_end_time;
                $req_data['settle_model_start_time'] = $settle_model_start_time;
            }
            $custominfo = Custom::where(['cpid' => $cpid, 'category' => 2, 'id' => $req_data['custom_id'], 'custom_status' => 3, 'is_freeze' => 1])->first();
            if (!$custominfo) {
                return response()->json(['code' => '001', 'msg' => '无效供应商信息']);
            }
            $settlecompany = SettleCompany::where(['cpid' => $cpid, 'id' => $req_data['pa_settle_company_id'], 'status' => 1])->first();
            if (!$settlecompany) {
                return response()->json(['code' => '001', 'msg' => '无效结算公司信息']);
            }

            if (intval($req_data['sales_manger_id']) > 0) {
                $sales_mangerinfo = Manger::where(['cpid' => $cpid, 'id' => $req_data['sales_manger_id'], 'status' => 1])->first();

                if (!$sales_mangerinfo) {
                    return response()->json(['code' => '001', 'msg' => '无效销售人员信息']);
                }
            } else {
                $req_data['sales_manger_id'] = 0;
                $sales_mangerinfo = null;
            }

            $maindata = [
                'cpid' => $cpid,
                'manger_id' => $this->mangerinfo['id'],
                'pa_id' => 0,
                'pa_type' => $pa_type,
                'custom_id' => $custominfo->id,
                'company_name' => $custominfo->company_name,
                'pa_contract_no' => '',
                'pa_sn_code' => '',
                'order_sn_code' => SnCode::getSnCode('PO_'),
                'pa_settle_company_id' => $settlecompany->id,
                'pa_settle_company_name' => $settlecompany->settle_company_name,
                'sales_manger_id' => $req_data['sales_manger_id'],
                'sales_manger_name' => isset($sales_mangerinfo->realname) ? $sales_mangerinfo->realname : '',
                'order_date' => strtotime($req_data['order_date']),
                'invoice_type' => $req_data['invoice_type'],
                'settle_model' => $req_data['settle_model'],
                'settle_model_start_time' => $req_data['settle_model_start_time'],
                'settle_model_end_time' => $req_data['settle_model_end_time'],
                'remark' => $req_data['remark'] ? $req_data['remark'] : '',
                'create_at' => time(),
                'update_at' => time(),
                'is_band' => 2
            ];
        }

        if (intval($req_data['pa_id']) > 0) {
            $ValidateSub = new PurchasePurchaseOrder('subadd');
        } else {
            $ValidateSub = new PurchasePurchaseOrder('subaddbyform');
        }

        $suborderdata = [];
        $order_weight = 0;
        $order_count = 0;
        $order_money = 0;
        foreach ($suborder as $s_order) {
            $s_order = is_array($s_order) ? $s_order : json_decode($s_order, true);
            if (!$ValidateSub->check($s_order)) { //初筛过滤
                return response()->json(['code' => '001', 'msg' => $ValidateSub->getError()]);
            }





            //锁价、点价、后结算取价不一样，点价获取协议价格
            if (intval($req_data['pa_id']) > 0) { //有协议按照协议价格，无协议手动输入
                $price_arr = ['price' => $painfo['price'], 'base_price' => $painfo['price'], 'add_price' => 0];
                $price = $price_arr['price'];
            } else {
                $s_order['add_price'] = isset($s_order['add_price']) ? intval($s_order['add_price']) : 0;
                $price_arr = ['price' => mathfuncmoney('add', $s_order['base_price'], $s_order['add_price']), 'base_price' => $s_order['base_price'], 'add_price' => $s_order['add_price']];
                $price = $price_arr['price'];
            }

            $stockinfo = Stock::where('id', $s_order['stock_id'])->first();
            if (!$stockinfo) {
                return response()->json(['code' => '001', 'msg' => '无效库存信息']);
            }
            $stockinfo = $stockinfo->toArray();


            if (in_array($stockinfo['archive_type'], [1, 2, 3])) {
                if (isset($s_order['count']) && intval($s_order['count']) > 0) {
                    $s_order['count'] = intval($s_order['count']);
                } else {
                    return response()->json(['code' => '001', 'msg' => '请输入数量']);
                }
            }


            if (in_array($stockinfo['archive_type'], [2, 3, 4])) {
                if (isset($s_order['total_weight']) && doubleval($s_order['total_weight']) > 0) {
                    $s_order['total_weight'] = doubleval($s_order['total_weight']);
                } else {
                    return response()->json(['code' => '001', 'msg' => '请输入总重']);
                }
                $s_order['count'] = intval($s_order['count']);
            }



            $s_order['price'] = $price;
            if ($stockinfo['archive_type'] == 3) { //定尺
                $s_order['weight'] = mathtoweightbyarchivetype($stockinfo['archive_spec'], $stockinfo['archive_type']);

                $s_order['total_weight'] = mathfuncweight('mul', $s_order['weight'], $s_order['count'], 1);
            } elseif ($stockinfo['archive_type'] == 2) { //过磅
                $s_order['weight'] = mathfunc('div', $s_order['total_weight'], $s_order['count'], 1);
            } elseif ($stockinfo['archive_type'] == 1) { //理计，理计初始化和过磅一样，取总重和件数

                $s_order['weight'] = mathfuncweight('div', $s_order['total_weight'], $s_order['count'], 1);
            }
            //total_weight--kg,price--分，total_money--分
            $s_order['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $s_order['total_weight'], 1000, 4), $s_order['price'], 0);

            $item = [
                'cpid' => $cpid,
                'stock_id' => $stockinfo['id'],
                'count' => $s_order['count'],
                'weight' => $s_order['weight'],
                'total_weight' => $s_order['total_weight'],
                'price' => $price,
                'base_price' => $price_arr['base_price'],
                'add_price' => $price_arr['add_price'],
                'total_money' => intval($s_order['total_money']),
                'warehouse_name' => $stockinfo['warehouse_name'],
                'archive_no' => $stockinfo['archive_no'],
                'archive_name' => $stockinfo['archive_name'],
                'archive_spec' => $stockinfo['archive_spec'],
                'archive_material' => $stockinfo['archive_material'],
                'steel_factory_name' => $stockinfo['steel_factory_name'],
                'breed_name' => $stockinfo['breed_name'],
                'archive_type' => $stockinfo['archive_type'],
                'remark' => isset($s_order['remark']) ? $s_order['remark'] : ''
            ];
            $item = TableExtFeild::setFeildToData($s_order, $item);
            $processitem = [
                'cpid' => $cpid,
                'stock_id' => $stockinfo['id'],
                'warehouse_name' => $stockinfo['warehouse_name'],
                'archive_no' => $stockinfo['archive_no'],
                'archive_name' => $stockinfo['archive_name'],
                'archive_spec' => $stockinfo['archive_spec'],
                'archive_material' => $stockinfo['archive_material'],
                'steel_factory_name' => $stockinfo['steel_factory_name'],
                'breed_name' => $stockinfo['breed_name'],
                'archive_type' => $stockinfo['archive_type'],
                'price' => $price,
                'base_price' => $price_arr['base_price'],
                'add_price' => $price_arr['add_price'],
                'order_weight' => $s_order['total_weight'],
                'order_count' => $s_order['count'],
                'order_money' => intval($s_order['total_money']),
            ];
            $item['processitem'] = $processitem;
            $suborderdata[] = $item;

            $order_weight = mathfuncweight('add', $order_weight, $s_order['total_weight'], 1);
            $order_count = mathfunc('add', $order_count, $s_order['count']);
            $order_money = mathfuncmoney('add', $order_money, intval($s_order['total_money']));

//            //获取存货信息和金额信息
//            $ChanjetVoucherDetails[] = [
//                "Inventory" => [
//                    "Code" => $stockinfo['archive_no'],
//                ],
//                "Quantity" => $order_count,
//                "Unit" => ["name" => "吨"],
//                "OrigDiscountAmount" => $s_order['total_money'],
//                "DynamicPropertyKeys" => ["pubuserdefnvc1", "pubuserdefnvc2", "pubuserdefnvc3"],
//                "DynamicPropertyValues" => [$stockinfo['steel_factory_name'], $stockinfo['breed_name'], $stockinfo['archive_material']],
//            ];
        }

        //其他费用
        $otherfeedata = [];
        $ValidateSub = new PurchasePurchaseOrder('otherfee');
        foreach ($otherfee as $fee) {
            $fee = is_array($fee) ? $fee : json_decode($fee, true);
            if (!$ValidateSub->check($fee)) { //初筛过滤
                return response()->json(['code' => '001', 'msg' => $ValidateSub->getError()]);
            }
            $fee_type_info = FeeType::where(['cpid' => $cpid, 'id' => $fee['fee_type_id'], 'category' => 2, 'status' => 1, 'is_del' => 1])->first();
            if (!$fee_type_info) {

                return response()->json(['code' => '001', 'msg' => '费用类型参数错误']);
            }
            $fee['fee_date'] = isset($fee['fee_date']) ? ((strtotime($fee['fee_date']) > 0) ? strtotime($fee['fee_date']) : intval($fee['fee_date'])) : 0;
            if ($fee['fee_date'] < 0) {
                return response()->json(['code' => '001', 'msg' => '费用日期格式错误']);
            }
            $otherfeedata[] = [
                'cpid' => $cpid,
                'fee_type_id' => $fee['fee_type_id'],
                'fee_type_name' => $fee_type_info->type_name,
                'fee_date' => $fee['fee_date'],
                'fee_name' => $fee['fee_name'],
                'company_name' => $fee['company_name'],
                'price' => $fee['price'],
                'remark' => isset($fee['remark']) ? strval($fee['remark']) : '',
            ];
        }

        $mainprocessdata = [
            'cpid' => $cpid,
            'manger_id' => $this->mangerinfo['id'],
            'pa_id' => $maindata['pa_id'],
            'pa_type' => $maindata['pa_type'],
            'custom_id' => $maindata['custom_id'],
            'company_name' => $maindata['company_name'],
            'pa_settle_company_id' => $maindata['pa_settle_company_id'],
            'pa_settle_company_name' => $maindata['pa_settle_company_name'],
            'sales_manger_id' => $maindata['sales_manger_id'],
            'sales_manger_name' => $maindata['sales_manger_name'],
            'order_date' => $maindata['order_date'],
            'settle_model' => $maindata['settle_model'],
            'order_weight' => $order_weight,
            'order_count' => $order_count,
            'order_money' => $order_money,
            'create_at' => time(),
            'update_at' => time(),
            'po_order_sn_code' => $maindata['order_sn_code']
        ];

        $maindata = TableExtFeild::setFeildToData($req_data, $maindata);

        DB::beginTransaction();
        try {
            $order_id = PurchaseOrder::create($maindata)->id;
            $mainprocessdata['order_id'] = $order_id;
            //更新重量格式
            $mainprocessdata['order_weight'] = mathfuncweight('mul', $mainprocessdata['order_weight'], 10, 0);
            $process_order_id = PurchaseOrderProcess::create($mainprocessdata)->id;
            foreach ($suborderdata as $key => $val) {
                $suborderdata[$key]['order_id'] = $order_id;
                $processitem = $val['processitem'];
                unset($suborderdata[$key]['processitem']);

                //更新重量格式
                $suborderdata[$key]['weight'] = mathfuncweight('mul', $suborderdata[$key]['weight'], 10, 0);
                $suborderdata[$key]['total_weight'] = mathfuncweight('mul', $suborderdata[$key]['total_weight'], 10, 0);

                $sub_order_id = PurchaseOrderSub::create($suborderdata[$key])->id;
                $processitem['process_order_id'] = $process_order_id;
                $processitem['sub_order_id'] = $sub_order_id;
                $processitem['order_id'] = $order_id;
                //更新重量格式
                $processitem['order_weight'] = mathfuncweight('mul', $processitem['order_weight'], 10, 0);
                PurchaseOrderProcessSub::create($processitem);
            }

            //其他费用
            foreach ($otherfeedata as $key => $val) {
                $otherfeedata[$key]['order_id'] = $order_id;
                PurchaseOrderOtherfee::create($otherfeedata[$key]);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            SnCode::rollBackSnCode('PO_');
            return response()->json(['code' => '001', 'msg' => '采购订单新增失败' . $e->getMessage()]);
        }

        /**
         *  采购订单
         *
         *
        */
//        $chanjet_param = [
//            "dto"=>[
//                "ExternalCode"=>$maindata["order_sn_code"],
//                "VoucherDate"=>date('Y-m-d',strtotime($req_data['order_date'])),
//                "BusinessType" => ["Code" =>"01"],//01 普通采购 02 采购退货
//                "Partner" => [
//                    "Code" => Custom::where('id',$maindata['custom_id'])->value("company_code"),
//                    "Name" => Custom::where('id',$maindata['custom_id'])->value("company_name"),
//                ],
//                "VoucherDetails" => $ChanjetVoucherDetails
//            ]
//        ];
//        if(!empty($stockinfo['warehouse_id'])){
//            $chanjet_warehouse_no = WarehouseList::where('id',$stockinfo['warehouse_id'])->value('warehouse_no');
//            $chanjet_param["dto"][] = ["Warehouse"=>["Code"=>$chanjet_warehouse_no]];
//        }
//        if($this->mangerinfo['org_id']) {
//            ChanjetRequest::getInstance()->purchaseOrderCreate($chanjet_param,$this->mangerinfo['org_id']);
//        }

        return response()->json(['code' => '000', 'msg' => '采购订单新增成功']);
    }



    public function dopostimprove(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];

        $info = PurchaseOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1, 'is_from_sale' => 2])
            ->first();

        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        if ($info->is_completion != 2) {
            return response()->json(['code' => '001', 'msg' => '订单已补全，不可重复操作']);
        }

        $finishcount = PurchaseOrderProcess::where(['order_id' => $order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
        if ($finishcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可编辑']);
        }

        // 检查是否存在单价为0的子订单
        $hasZeroPrice = PurchaseOrderSub::where('order_id', $order_id)
            ->where('is_del', 1)
            ->where('cpid', $cpid)
            ->where('price', 0)
            ->exists();

        if ($hasZeroPrice) {
            return response()->json(['code' => '001', 'msg' => '存在单价为0的子订单，请先修改价格']);
        }

        $req_data = $request->only([
            'pa_id',
            'remark',
            'custom_id',
            'pa_settle_company_id',
            'settle_model',
            'invoice_type',
            'settle_model_start_time',
            'settle_model_end_time',
            'field_1',
            'field_2',
            'field_3',
            'field_4',
            'field_5',
            'field_6',
            'field_7',
            'field_8',
            'field_9',
            'field_10'
        ]);

        if (!(isset($req_data['pa_id']) && intval($req_data['pa_id']) > 0)) {
            return response()->json(['code' => '001', 'msg' => '合同信息必填']);
        }

        $painfo = PurchaseAgreement::with([
            'mangerinfo' => function ($query) {
                $query->select(['id', 'realname', 'username']);
            },
            'custominfo' => function ($query) {
                $query->select(['id', 'company_name']);
            },
            'settlecompany' => function ($query) {
                $query->select(['id', 'settle_no', 'settle_company_name']);
            },

        ])->where([['id', $req_data['pa_id']], ['cpid', $cpid]])->first();
        if (!$painfo) {
            return response()->json(['code' => '001', 'msg' => '无效合同信息']);
        }
        $painfo = $painfo->toArray();

        if ($painfo['type'] != 4) {
            return response()->json(['code' => '001', 'msg' => '合同必须为业务自采类型']);
        }



        $maindata = [
            'pa_id' => isset($req_data['pa_id']) ? $req_data['pa_id'] : 0,
            'custom_id' => $painfo['custom_id'],
            'company_name' => $painfo['custominfo']['company_name'],
            'pa_contract_no' => $painfo['contract_no'],
            'pa_sn_code' => $painfo['sn_code'],
            'pa_settle_company_name' => $painfo['settlecompany']['settle_company_name'],
            'invoice_type' => $painfo['invoice_type'],
            'settle_model' => $painfo['settle_model'],
            'remark' => isset($req_data['remark']) ? $req_data['remark'] : '',
            'pa_settle_company_id' => $painfo['settlecompany']['id'],
            'settle_model_start_time' => $painfo['settle_model_start_time'],
            'settle_model_end_time' => $painfo['settle_model_end_time'],
            'is_band' => 1
        ];


        $pmaindata = [
            'pa_id' => isset($req_data['pa_id']) ? $req_data['pa_id'] : 0,
            'custom_id' => $painfo['custom_id'],
            'company_name' => $painfo['custominfo']['company_name'],

            'pa_settle_company_name' => $painfo['settlecompany']['settle_company_name'],

            'settle_model' => $painfo['settle_model'],
            'pa_settle_company_id' => $painfo['settlecompany']['id'],

        ];


        PurchaseOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1, 'is_from_sale' => 2])->update($maindata);
        PurchaseOrderProcess::where(['order_id' => $order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->update($pmaindata);
        return response()->json(['code' => '000', 'msg' => '采购订单补全成功']);
    }

    /**
     * 修改采购订单，订单已支付或者已生成则不可修改
     *
     * 已销定采订单，采购子订单修改后，需要同步到销售订单，
     * 目前同步到采购的子订单 只允许，修改/删除 不可新增。2025.05.21 王丹娜
     *
     *
     *
     */
    public function dopostedit(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];

        if ($this->mangerinfo['utype'] == 4) {
            $info = PurchaseOrder::where(['id' => $order_id, 'cpid' => $cpid, 'is_del' => 1])->with('suborder')->first();
        } else {
            $info = PurchaseOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->with('suborder')->first();
        }

        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        if ($this->mangerinfo['utype'] == 6 && $info->is_finance_update != 1) {
            return response()->json(['code' => '001', 'msg' => '统审端修改后，采购不可修改']);
        }





        //如果未绑定协议，则可以修改表头信息
        // if($info->pa_id<=0){
        //     $req_data = $request->only([
        //         'pa_id', 'order_date', 'remark',
        //         'pa_type','custom_id','pa_settle_company_id','sales_manger_id','settle_model','invoice_type','settle_model_start_time','settle_model_end_time'
        //     ]);
        // }

        //判断是否完结
        $finishcount = PurchaseOrderProcess::where(['order_id' => $order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
        if ($finishcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可编辑']);
        }


        //修改的信息只可修改子订单信息

        $suborder = is_array($request->suborder) ? $request->suborder : (is_array(json_decode($request->suborder, true)) ? json_decode($request->suborder, true) : []);
        if (count($suborder) <= 0) {
            return response()->json(['code' => '001', 'msg' => '订单数据不能为空']);
        }
        $cpid = $this->mangerinfo['cpid'];
        if ($info->is_from_sale == 2) {
            $ValidateSub = new PurchasePurchaseOrder('subeditbysale');
        } else {
            if ($info->is_band == 1) {
                $ValidateSub = new PurchasePurchaseOrder('subedit');
            } else {
                $ValidateSub = new PurchasePurchaseOrder('subeditbyform');
            }
        }


        $suborderdata = [];
        $order_weight = 0;
        $order_count = 0;
        $order_money = 0;
        $suborderkey = [];
        foreach ($suborder as $s_order) {
            $s_order = is_array($s_order) ? $s_order : json_decode($s_order, true);
            if (!$ValidateSub->check($s_order)) { //初筛过滤
                return response()->json(['code' => '001', 'msg' => $ValidateSub->getError()]);
            }
            //判断子订单是否存在
            $suborderinfo = PurchaseOrderSub::where(['cpid' => $cpid, 'order_id' => $order_id, 'id' => $s_order['id'], 'is_del' => 1])->first();
            if (!$suborderinfo || $s_order['stock_id'] != $suborderinfo->stock_id) { //只可修改件数，重量等相关数据
                return response()->json(['code' => '001', 'msg' => '无效参数']);
            }
            $suborderinfo = $suborderinfo->toArray();
            $suborderkey[] = $suborderinfo['id'];
            if ($suborderinfo['create_status'] != 1) { //已生成则不可修改数据跳过
                $order_weight = mathfuncweight('add', $order_weight, $suborderinfo['total_weight'], 1); //kg
                $order_count = mathfunc('add', $order_count, $suborderinfo['count']);
                $order_money = mathfuncmoney('add', $order_money, intval($suborderinfo['total_money']));
                continue;
            }

            $update_item = [];
            /****
             *   接收到的需求，已销定采
             *   定尺（单重固定）可修改 件数变化，重量也变化
             *
             *
            */
            if ($info->is_from_sale == 2) { //以销定采，件数、重量不允许修改

                //$s_order['count'] = $suborderinfo['count'];
                //$s_order['total_weight'] = $suborderinfo['total_weight']; //kg
            }
            if ($suborderinfo['archive_type'] == 3) { //定尺
                $total_weight = mathfuncweight('mul', $suborderinfo['weight'], $s_order['count'], 1);
                $update_item['total_weight'] = $total_weight; //kg
                $update_item['count'] =  $s_order['count'];
                $update_item['weight'] = $suborderinfo['weight']; //kg
            } elseif ($suborderinfo['archive_type'] == 1 || $suborderinfo['archive_type'] == 2 || $suborderinfo['archive_type'] == 4) { //过磅//理计，理计初始化和过磅一样，取总重和件数
                $total_weight = $s_order['total_weight']; //kg
                $update_item['total_weight'] = $total_weight; //kg
                $update_item['count'] =  $s_order['count'];
                $update_item['weight'] = mathfuncweight('div', $s_order['total_weight'], $s_order['count'], 1); //kg
            }
            //total_weight--kg,price--分，total_money--分
            if ($info->is_from_sale == 2) {

                $update_item['base_price'] = $s_order['base_price'];
                $update_item['add_price'] =  $s_order['add_price'];
                //$update_item['price'] =  $s_order['price'];
                $update_item['price'] =  $s_order['base_price'] + $s_order['add_price'];
                //$update_item['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $total_weight, 1000, 4), $suborderinfo['price'], 0);
                $update_item['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $total_weight, 1000, 4), $update_item['price'], 0);
            } else {
                if ($info->is_band == 1) {
                    $update_item['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $total_weight, 1000, 4), $suborderinfo['price'], 0);
                } else {
                    $update_item['base_price'] =  $s_order['base_price'];
                    $update_item['add_price'] =  $s_order['add_price'];
                    $update_item['price'] =  mathfuncmoney('add', $s_order['base_price'], $s_order['add_price']);
                    $update_item['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $total_weight, 1000, 4), $update_item['price'], 0);
                }
            }

            $update_item['remark'] = $s_order['remark'];

            $order_weight = mathfuncweight('add', $order_weight, $total_weight, 1);
            $order_count = mathfunc('add', $order_count, $update_item['count']);
            $order_money = mathfuncmoney('add', $order_money, intval($update_item['total_money']));
            $update_item['sale_sub_id'] = $suborderinfo['sale_sub_id'];
            $suborderdata[$suborderinfo['id']] = $update_item;
        }
        if(count($suborderdata)<=0){
            return response()->json(['code' => '001', 'msg' => '当期没有可以修改的数据']);
        }
        //查询销售订单执行表的所有子订单
        $order_number = $info->sale_order_number;
        $Saleimplementation = Saleimplementation::with(['suborder' => function ($query) {
                $query->where('is_del', config('constants.is_del.no'));
            }])->where('order_number', $order_number)
            ->where('is_del', config('constants.is_del.no'))
            ->first();
        if(!empty($Saleimplementation))
        {
            $Saleimplementation = $Saleimplementation->toArray();
        }

        DB::beginTransaction();
        try {
            $updatedata = ['remark' => strval($request->remark), 'update_at' => time()];

            if ($this->mangerinfo['utype'] == 4) {

                $updatedata['is_finance_update'] = 2;
            }

            PurchaseOrder::where(['id' => $order_id, 'cpid' => $cpid, 'is_del' => 1])->update($updatedata);
            /***
             * 已销定采，更新销售订单执行表
             *
             *
             */
            $updateSaleImplementAtion = ['sale_weight'=>0,'sale_amount'=>0,'sale_pieces'=>0];

            $is_from_sale_arr = [];
            $sale_sub_ids = [];
            $SaleorderController = new SaleorderController($request);
            foreach ($suborderdata as $key => $val) {
                //更新重量格式
                $val['weight'] = mathfuncweight('mul', $val['weight'], 10, 0); //kg*10
                $val['total_weight'] = mathfuncweight('mul', $val['total_weight'], 10, 0); //kg*10
                PurchaseOrderSub::where(['cpid' => $cpid, 'order_id' => $order_id, 'id' => $key])->update($val);
                PurchaseOrderProcessSub::where(['cpid' => $cpid, 'sub_order_id' => $key])->update(['order_weight' => $val['total_weight'], 'order_count' => $val['count'], 'order_money' => $val['total_money']]);

                if ($info->is_from_sale == 2) {
                    //----------------返库存(同时获取到销售订单-单价)-----扣返库存通用方法，传入二维数组 get获取---------
                    $orgSaleordersub = ModelSaleordersub::where(['id' => $val['sale_sub_id'],'is_del' => 1])->get();

                    $incr_stock = $SaleorderController->incrDecrStockInSaleEdit($orgSaleordersub,'incr','g');
                    if($incr_stock['code'] != '000'){
                        return response()->json($incr_stock);
                    }
                    //----------------返库存--------------

                    $sale_order_unit_price = $orgSaleordersub[0]['unit_price']??0;
                    $total_weight_ton = mathfuncweight('div',$val['total_weight'],10000,4);
                    $sale_order_total = mathfuncmoney('mul',$sale_order_unit_price,$total_weight_ton,2);

                    $ModelSaleordersub = ModelSaleordersub::where(['id' => $val['sale_sub_id'],'is_del' => 1])->first();
                   if($ModelSaleordersub){
                       $ModelSaleordersub->total_weight = $val['total_weight'];
                       $ModelSaleordersub->weight = $val['weight'];
                       $ModelSaleordersub->pieces = $val['count'];
                       $ModelSaleordersub->total = $sale_order_total;
                       $ModelSaleordersub->save();
                   }
                    $Saleimplementationsub = Saleimplementationsub::where(['is_del' => 1,'sale_id'=>$val['sale_sub_id']])->first();
                    if($Saleimplementationsub){
                        $Saleimplementationsub->pieces = $val['count'];
                        $Saleimplementationsub->total = $sale_order_total;
                        $Saleimplementationsub->sale_weight = $val['total_weight'];
                        $Saleimplementationsub->sale_pieces = $val['count'];
                        $Saleimplementationsub->sale_amount = $sale_order_total;
                        $Saleimplementationsub->save();


                        $updateSaleImplementAtion['sale_weight'] += $Saleimplementationsub->sale_weight;
                        $updateSaleImplementAtion['sale_pieces'] += $Saleimplementationsub->sale_pieces;
                        $updateSaleImplementAtion['sale_amount'] += $Saleimplementationsub->sale_amount;
                        $sale_sub_ids[] = $val['sale_sub_id'];
                    }

                    //----------------扣库存--------------
                    $newSaleordersub = ModelSaleordersub::where(['id' => $val['sale_sub_id'],'is_del'=>1])->get();
                    $decr_stock = $SaleorderController->incrDecrStockInSaleEdit($newSaleordersub,'decr','g');
                    if($decr_stock['code'] != '000'){
                        return response()->json($decr_stock);
                    }
                    //----------------扣库存---------------

                    $is_from_sale_arr[] = $val['sale_sub_id'];

                    //重新计算 计提/业绩
                    $SaleorderController->getaccrualsysp($cpid,$val['sale_sub_id'],$val['price']);
                }
            }
            //更新销售订单执行表
            if($info->is_from_sale == 2 && isset($info->sale_order_number)){

                //还需要增加销售订单对应多个采购订单的时候 不在这个采购订单的销售子订单数量
                if($Saleimplementation['suborder']){
                    foreach ($Saleimplementation['suborder'] as $val)
                    {
                        if(!in_array($val['sale_id'],$sale_sub_ids)){
                            $updateSaleImplementAtion['sale_weight'] += $val['sale_weight'];
                            $updateSaleImplementAtion['sale_pieces'] += $val['sale_pieces'];
                            $updateSaleImplementAtion['sale_amount'] += $val['sale_amount'];
                        }
                    }
                }

                Saleimplementation::where(['is_del'=>1,'cpid'=>$cpid,'order_number'=>$info->sale_order_number])
                    ->update($updateSaleImplementAtion);
            }

            PurchaseOrderSub::where(['cpid' => $cpid, 'order_id' => $order_id, 'create_status' => 1])->whereNotIn('id', $suborderkey)->update(['is_del' => 2, 'del_at' => time()]); //删除订单子订单

            $sale_pid=ModelSaleorder::where(['order_number' => $info->sale_order_number,'is_del'=>1,'cpid'=>$cpid])->value('id');

            /****
             *  已销定采场景，采购修改后，同步到销售
             *  删除 初始/上一次非自采 销售子订单数据
             *
             *  采购修改，只能修改/删除；提交后，子id未获取到，认为被删除。获取到的 认为是修改
             *
            */
            if ($info->is_from_sale == 2) {
                ModelSaleordersub::where('p_id', $sale_pid)
                    ->whereNotIn('id', $is_from_sale_arr)
                    ->whereIn('id', explode(',',$info->sale_sub_ids))
                    ->update([
                        'is_del' => 2,
                        'del_at' => time()
                    ]);
            }

            PurchaseOrderProcessSub::where(['cpid' => $cpid, 'order_id' => $order_id]) //删除订单进度子订单
                ->whereNotIn('sub_order_id', $suborderkey)->update(['is_del' => 2, 'del_at' => time()]);

            /**
             * 处理订单进度
             */
            //更新重量格式
            $order_weight = mathfuncweight('mul', $order_weight, 10, 0);
            PurchaseOrderProcess::where(['cpid' => $cpid, 'order_id' => $order_id])->update(['order_weight' => $order_weight, 'order_count' => $order_count, 'order_money' => $order_money]);


            $editlog = ['cpid' => $cpid, 'order_type' => 1, 'order_sn_code' => $info->order_sn_code, 'before_data' => json_encode($info), 'editor_mid' => $this->mangerinfo['id'], 'editor_realname' => $this->mangerinfo['realname'], 'create_at' => time()];
            $editlog['after_data'] = json_encode(PurchaseOrder::where(['id' => $order_id, 'cpid' => $cpid, 'is_del' => 1])->with('suborder')->first());

            EditLog::create($editlog);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '采购订编辑失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 绑定协议
     */
    public function doorderbindpa(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];

        $info = PurchaseOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1, 'is_band' => 2])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        if ($info->pa_id > 0) {
            return response()->json(['code' => '001', 'msg' => '订单协议已存在，无法重复绑定']);
        }

        $pa_id = $request->pa_id ?? 0;
        $painfo = PurchaseAgreement::where([['id', $pa_id], ['cpid', $this->mangerinfo['cpid']], ['manger_id', $this->mangerinfo['id']]])->first();
        if (!$painfo) {
            return response()->json(['code' => '001', 'msg' => '无效协议信息']);
        }

        $info = $info->toArray();
        $painfo = $painfo->toArray();
        //
        //&& $painfo['settle_model_start_time']==$info['settle_model_start_time'] && $painfo['settle_model_end_time']==$info['settle_model_end_time']
        if($painfo['type'] != $info['pa_type']){
            return response()->json(['code' => '000', 'msg' => '合同和订单，类型不一致']);
        }
        if($painfo['custom_id'] != $info['custom_id']){
            return response()->json(['code' => '000', 'msg' => '合同和订单，供应商信息不一致']);
        }
        if($painfo['settle_company_id'] != $info['pa_settle_company_id']){
            return response()->json(['code' => '000', 'msg' => '合同和订单，结算公司不一致']);
        }
        if($painfo['sales_manger_id'] != $info['sales_manger_id']){
            return response()->json(['code' => '000', 'msg' => '合同和订单，业务员账号不一致']);
        }
        if($painfo['settle_model'] != $info['settle_model']){
            return response()->json(['code' => '000', 'msg' => '合同和订单，结算模式不一致']);
        }
        if($painfo['invoice_type'] != $info['invoice_type']){
            return response()->json(['code' => '000', 'msg' => '合同和订单，票据类型不一致']);
        }
        $update = ['pa_id' => $pa_id, 'pa_contract_no' => $painfo['contract_no'], 'pa_sn_code' => $painfo['sn_code'], 'is_band' => 3];

        if($info['settle_model'] == 3 && $info['settle_model_start_time'] == 0 && $info['settle_model_end_time'] == 0)
        {
            $update['settle_model_start_time'] = $painfo['settle_model_start_time'];
            $update['settle_model_end_time'] = $painfo['settle_model_end_time'];
        }

        PurchaseOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->update($update);
        return response()->json(['code' => '000', 'msg' => '绑定协议成功']);
    }

    /**
     * 获取订单列表
     */
    public function getorderlist(Request $request)
    {
        $isgetall = $request->isgetall ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        if ($this->mangerinfo['utype'] != 6) {
            $manger_id = 0; //查询所有订单
        }
        $list = PurchaseOrder::getList($request, $cpid, $manger_id, $isgetall);
        //计算子订单数据到主订单
        $list['list'] = PurchaseCommon::getOrderSum($list['list']);


        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }
    /**
     * 获取订单详情
     */
    public function getorderinfo(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = PurchaseOrder::where(['id' => $order_id,  'cpid' => $cpid, 'is_del' => 1])->with(['suborder', 'otherfee', 'createmangerinfo','mangerinfo'])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        $info->balance = Balance::where(['category' => 2, 'cpid' => $cpid, 'custom_id' => $info->custom_id])->value('balance');
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['info' => $info]]);
    }

    /**
     * 删除订单
     */
    public function doorderdel(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = PurchaseOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->with('suborder')->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        if ($info->is_from_sale == 2) {
            return response()->json(['code' => '001', 'msg' => '自采订单无法删除']);
        }

        //判断是否完结
        $finishcount = PurchaseOrderProcess::where(['order_id' => $order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
        if ($finishcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可删除']);
        }
        //如果有生成进货单的订单就不能删除
        $jhcount = PurchaseStockinOrder::where(['order_id' => $order_id, 'cpid' => $cpid, 'is_del' => 1])->count();
        if ($jhcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已生成进货单，不可删除']);
        }

        $subcount = PurchaseOrderSub::where([['order_id', $order_id], ['cpid', $cpid], ['pay_status', '<>', 1]])
            ->orWhere([['order_id', $order_id], ['cpid', $cpid], ['create_status', '<>', 1]])->count();

        if ($subcount > 0) {
            return response()->json(['code' => '001', 'msg' => '存在已生成或已付款订单']);
        }

        DB::beginTransaction();
        try {
            PurchaseOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid])->update(['is_del' => 2, 'del_at' => time()]);

            PurchaseOrderSub::where(['order_id' => $order_id])->update(['is_del' => 2, 'del_at' => time()]);
            PurchaseOrderOtherfee::where(['order_id' => $order_id])->update(['is_del' => 2, 'del_at' => time()]);

            //删除订单进度
            PurchaseOrderProcess::where(['order_id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid])->update(['is_del' => 2, 'del_at' => time()]);
            PurchaseOrderProcessSub::where(['order_id' => $order_id, 'cpid' => $cpid])->update(['is_del' => 2, 'del_at' => time()]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '采购订单删除失败' . $e->getMessage()]);
        }


        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    public function doorderdelaudit(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $del_audit_status = $request->del_audit_status ?? 0;
        $info = PurchaseOrder::where(['id' => $order_id,  'cpid' => $cpid, 'is_del' => 1])->with('suborder')->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        if (!in_array($del_audit_status, [3, 4])) {
            return response()->json(['code' => '001', 'msg' => '审核参数错误']);
        }

        if ($info->del_audit_status == 1) {
            return response()->json(['code' => '001', 'msg' => '订单未提交审核']);
        }
        if (in_array($info->del_audit_status, [3, 4])) {
            return response()->json(['code' => '001', 'msg' => '订单已审核']);
        }


        //判断是否完结
        $finishcount = PurchaseOrderProcess::where(['order_id' => $order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
        if ($finishcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可删除']);
        }
        $subcount = PurchaseOrderSub::where([['order_id', $order_id], ['cpid', $cpid], ['pay_status', '<>', 1]])->orWhere([['order_id', $order_id], ['cpid', $cpid], ['create_status', '<>', 1]])->count();

        if ($subcount > 0) {
            return response()->json(['code' => '001', 'msg' => '存在已生成或已付款订单']);
        }

        DB::beginTransaction();
        try {

            if ($del_audit_status == 3) {
                PurchaseOrder::where(['id' => $order_id,  'cpid' => $cpid])->update(['is_del' => 2, 'del_at' => time(), 'del_audit_status' => 3]);

                PurchaseOrderSub::where(['order_id' => $order_id])->update(['is_del' => 2, 'del_at' => time()]);
                PurchaseOrderOtherfee::where(['order_id' => $order_id])->update(['is_del' => 2, 'del_at' => time()]);

                //删除订单进度
                PurchaseOrderProcess::where(['order_id' => $order_id,  'cpid' => $cpid])->update(['is_del' => 2, 'del_at' => time()]);
                PurchaseOrderProcessSub::where(['order_id' => $order_id, 'cpid' => $cpid])->update(['is_del' => 2, 'del_at' => time()]);
            } else {
                PurchaseOrder::where(['id' => $order_id,  'cpid' => $cpid])->update(['del_audit_status' => 4]);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '采购订单删除失败' . $e->getMessage()]);
        }


        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 编辑表头字段
     */
    public function changeorderfield(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $sub_order_id = $request->sub_order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = PurchaseOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $suborderinfo = PurchaseOrderSub::where(['order_id' => $order_id, 'id' => $sub_order_id, 'is_del' => 1])->first();
        $data = TableExtFeild::getTableFeildData($request);
        if ($suborderinfo) {
            PurchaseOrderSub::where(['order_id' => $order_id, 'id' => $sub_order_id, 'is_del' => 1])->update($data);
        } else {
            PurchaseOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->update($data);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 生成进货单
     * 更改数量，进行拆分
     * 需要传子订单数量、重量信息
     */
    public function createstockinorder(Request $request)
    {
        //[{"sub_order_id":1,"create_count":"5","create_weight":""},{"sub_order_id":2,"create_count":"2","create_weight":""}]
        // echo json_encode([['sub_order_id'=>1,'create_count'=>'5','create_weight'=>''],['sub_order_id'=>1,'create_count'=>'2','create_weight'=>'']]);exit;
        $order_id = $request->order_id ?? 0;
        $sub_order = is_array($request->sub_order) ? $request->sub_order : (is_array(json_decode($request->sub_order, true)) ? json_decode($request->sub_order, true) : []);

        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $carship_no = $request->carship_no ?? '';
        $remark = $request->remark ?? '';

        if ($carship_no == '') {
            return response()->json(['code' => '001', 'msg' => '车船号不能为空']);
        }
        $info = PurchaseOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        if ($info->pa_id <= 0) {
            return response()->json(['code' => '001', 'msg' => '协议信息不完整']);
        }

        //判断是否完结
        $finishcount = PurchaseOrderProcess::where(['order_id' => $order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
        if ($finishcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可生成进货单']);
        }

        //获取类型
        $ischeckpay = 0;
        if ($info->settle_model == 1 || $info->settle_model == 2) { //需要判断是否付款

            //需要判断预付单状态
            // $ischeckpay = 1;
        }
        $sub_order_arr = [];

        $Chanjet_VoucherDetails = []; //进货单详情

        if ($info->is_from_sale == 2) {
            //以销定采
//            $sub_order_list = $info->suborder()->get()->toArray();

            foreach ($sub_order as $v) {
                $v['create_count'] = $v['count'];
                $v['remark'] = isset($v['remark']) ? $v['remark'] : '';
                $v['weight'] = mathfuncweight('mul', $v['weight'], 10);
                $v['total_weight'] = mathfuncweight('mul', $v['total_weight'], 10);
                $sub_order_arr[] = $v;
            }
        } else {
            if (count($sub_order) > 0) {

                foreach ($sub_order as $val) {


                    if (isset($val['id']) && $val['id'] > 0) {
                        $sub_order_info = PurchaseOrderSub::where([['order_id', $order_id], ['cpid', $cpid], ['id', $val['id']]])->first();


                        if ($sub_order_info && $sub_order_info->archive_type == 4) {
                            continue;
                        }

                        if (!isset($val['create_count']) || $val['create_count'] <= 0) {
                            return response()->json(['code' => '001', 'msg' => '生成件数不能小于0!']);
                        }

                        if (!$sub_order_info) {
                            return response()->json(['code' => '001', 'msg' => '子订单不存在']);
                        }
                        $sub_order_info = $sub_order_info->toArray();


                        if ($info->is_band != 1) { //创建订单未绑定协议的，可以修改价格
                            if (!(isset($val['base_price']) && intval($val['base_price']) > 0) || !(isset($val['add_price']) && intval($val['add_price']) >= 0)) {
                                return response()->json(['code' => '001', 'msg' => '无效价格设置']);
                            }

                            $sub_order_info['base_price'] =  $val['base_price'];
                            $sub_order_info['add_price'] =  $val['add_price'];
                            $sub_order_info['price'] =  mathfuncmoney('add', $val['base_price'], $val['add_price']);
                        }

                        // if ($ischeckpay == 1 && $sub_order_info['pay_status'] != 3) {
                        //     return response()->json(['code' => '001', 'msg' => '点价、锁价模式需支付成功才可生成']);
                        // }
                        if ($sub_order_info['archive_type'] == 3) {
                            //重量转换格式
                            $sub_order_info['total_weight'] = mathfuncweight('mul', mathfuncweight('mul', $sub_order_info['weight'], $val['create_count'], 1), 10); //kg*10
                            $sub_order_info['weight'] = mathfuncweight('mul', $sub_order_info['weight'], 10); //kg*10
                        }


                        if ($sub_order_info['archive_type'] == 1 || $sub_order_info['archive_type'] == 2) {
                            if ((!isset($val['create_weight']) || $val['create_weight'] <= 0)) {
                                return response()->json(['code' => '001', 'msg' => '过磅重量不能小于0']);
                            }
                            //重量转换格式
                            $sub_order_info['total_weight'] = mathfuncweight('mul', $val['create_weight'], 10); //kg*10

                            $sub_order_info['weight'] = mathfuncweight('div', $sub_order_info['total_weight'], $val['create_count']); //kg*10
                        }
                        $sub_order_info['create_count'] = $val['create_count'];
                        //total_weight-kg/10,price-fen,total_money-fen
                        $sub_order_info['total_money'] = mathfuncmoney('mul', mathfuncweight('div', $sub_order_info['total_weight'], 10000, 5), $sub_order_info['price'], 0);
                        $sub_order_info['remark'] = isset($val['remark']) ? $val['remark'] : '';
                        $sub_order_arr[] = $sub_order_info;

//                        //获取T+进货单 存货编码/数量/金额
//                        $Chanjet_VoucherDetails[] = [
//                            "Inventory" => ["Code" => $sub_order_info['archive_no']],
//                            "Quantity"  => $val['create_count'],
//                            "OrigDiscountAmount" => $sub_order_info['total_money'],
//                            "Warehouse" => ["Code" => WarehouseList::where(['warehouse_name' => $sub_order_info['warehouse_name'], 'cpid' => $cpid])->value('warehouse_no')],
//                            "DynamicPropertyKeys" => ["pubuserdefnvc1", "pubuserdefnvc2", "pubuserdefnvc3"],
//                            "DynamicPropertyValues" => [$sub_order_info['steel_factory_name'], $sub_order_info['breed_name'], $sub_order_info['archive_material']],
//                        ];
                    } else {
                        // continue;
                        if (!isset($val['create_count']) || $val['create_count'] <= 0) {
                            // Log::info($val);
                            return response()->json(['code' => '001', 'msg' => '生成件数不能小于0!!']);
                        }
                        $stockinfo = Stock::where('id', $val['stock_id'])->first();
                        if (!$stockinfo) {
                            return response()->json(['code' => '001', 'msg' => '无效库存信息']);
                        }
                        $stockinfo = $stockinfo->toArray();

                        $sub_order_info = [
                            'id' => $val['sub_order_id'],
                            'cpid' => $cpid,

                            'stock_id' => $val['stock_id'],
                            'create_count' => $val['create_count'],
                            'weight' => mathfuncweight('mul', $val['weight'], 10),
                            'total_weight' => mathfuncweight('mul', $val['create_weight'], 10),
                            'price' => $val['price'],
                            'base_price' => $val['base_price'],
                            'add_price' => $val['add_price'],
                            'total_money' => $val['total_money'],

                            'warehouse_name' => $stockinfo['warehouse_name'],
                            'archive_no' => $stockinfo['archive_no'],
                            'archive_name' => $stockinfo['archive_name'],
                            'archive_spec' => $stockinfo['archive_spec'],
                            'archive_material' => $stockinfo['archive_material'],
                            'steel_factory_name' => $stockinfo['steel_factory_name'],
                            'breed_name' => $stockinfo['breed_name'],
                            'archive_type' => $stockinfo['archive_type'],
                            'remark' => isset($val['remark']) ? $val['remark'] : ''
                        ];
                        $sub_order_arr[] = $sub_order_info;
                        //获取T+进货单 存货编码/数量/金额
//                        $Chanjet_VoucherDetails[] = [
//                            "Inventory" => ["Code" => $stockinfo['archive_no']],
//                            "Quantity"  => $val['create_count'],
//                            "OrigDiscountAmount" => $val['total_money'],
//                            "Warehouse" => ["Code" => WarehouseList::where(['warehouse_name' => $stockinfo['warehouse_name'], 'cpid' => $cpid])->value('warehouse_no')]
//                        ];
                    }
                }
            } else {
                //获取未生成的子订单
                return response()->json(['code' => '001', 'msg' => '子订单不能为空']);
            }
        }

        if (count($sub_order) <= 0) {
            return response()->json(['code' => '001', 'msg' => '子订单不能为空']);
        }

        $maindata = $info->toArray();
        $maindata['po_order_sn_code'] = $maindata['order_sn_code'];
        $maindata['order_sn_code'] = SnCode::getSnCode('PSO_');
        $maindata['order_id'] = $order_id;
        $maindata['create_at'] = time();
        $maindata['update_at'] = time();
        $maindata['carship_no'] = $carship_no;
        $maindata['remark'] = $remark;
        $maindata['is_finance_update'] = 1;

        $maindata['create_manger_id'] = $this->mangerinfo['id'];
        unset($maindata['id']);
        // unset($maindata['order_sn_code']);

        $suborderdata = [];
        $stockin_weight = 0;
        $stockin_count = 0;
        $stockin_money = 0;

        foreach ($sub_order_arr as $key => $val) {

            $item = [
                'old_sub_id' => $val['id'],
                'sub_order_id' => $val['id'],
                'cpid' => $cpid,
                'stock_id' => $val['stock_id'],
                'count' => $val['create_count'],
                'weight' => $val['weight'],
                'total_weight' => $val['total_weight'],
                'price' => $val['price'],
                'base_price' => $val['base_price'],
                'add_price' => $val['add_price'],
                'total_money' => $val['total_money'],
                'warehouse_name' => $val['warehouse_name'],
                'archive_no' => $val['archive_no'],
                'archive_name' => $val['archive_name'],
                'archive_spec' => $val['archive_spec'],
                'archive_material' => $val['archive_material'],
                'steel_factory_name' => $val['steel_factory_name'],
                'breed_name' => $val['breed_name'],
                'archive_type' => $val['archive_type'],
                'remark' => $val['remark']
            ];
            $stockin_weight = mathfuncweight('add', $stockin_weight, $val['total_weight']);
            $stockin_count = mathfunc('add', $stockin_count, $val['create_count']);
            $stockin_money = mathfuncmoney('add', $stockin_money, $item['total_money']);
            $suborderdata[] = $item;
        }
        DB::beginTransaction();
        try {
            $stockin_order_id = PurchaseStockinOrder::create($maindata)->id;

            /***
             *  已销定采,根据采购价 更新计提/业绩
             *
             *  当前更新逻辑，转移到 采购订单修改
             *
            */
            if ($info->is_from_sale == 2) {

                Saleorder::where(['cpid'=>$cpid, 'order_number'=>$info->sale_order_number])->update(['purchase_stockin_order_sn_code'=>$maindata['order_sn_code']]);

//                $Saleorder=new SaleorderController($request);
//                foreach ($sub_order_arr as $key => $val) {
//                    $Saleorder->getaccrualsysp($val['sale_sub_id'],$val['price']);
//                }

            }



            // $maindata['order_sn_code']

            PurchaseOrderProcess::where([['order_id', $order_id], ['cpid', $cpid]])
                ->update([
                    'stockin_weight' => DB::raw('stockin_weight + ' . $stockin_weight),
                    'stockin_count' => DB::raw('stockin_count + ' . $stockin_count),
                    'stockin_money' => DB::raw('stockin_money + ' . $stockin_money)
                ]);
            $old_sub_id_arr = [];
            foreach ($suborderdata as $key => $val) {
                $old_sub_id = $suborderdata[$key]['old_sub_id'];
                unset($suborderdata[$key]['old_sub_id']);
                $suborderdata[$key]['stockin_order_id'] = $stockin_order_id;
                PurchaseStockinOrderSub::insert($suborderdata[$key]);

                PurchaseOrderSub::where([['order_id', $order_id], ['cpid', $cpid], ['id', $old_sub_id]])
                    ->update(['create_count' => DB::raw('create_count + ' . $val['count']), 'create_weight' => DB::raw('create_weight + ' . $val['total_weight'])]);


                //更新订单执行情况
                PurchaseOrderProcessSub::where([['cpid', $cpid], ['sub_order_id', $old_sub_id]])
                    ->update([
                        'stockin_weight' => DB::raw('stockin_weight + ' . $val['total_weight']),
                        'stockin_count' => DB::raw('stockin_count + ' . $val['count']),
                        'stockin_money' => DB::raw('stockin_money + ' . $val['total_money'])
                    ]);
                $old_sub_id_arr[] = $old_sub_id;


            }
            PurchaseOrderSub::where([['order_id', $order_id], ['cpid', $cpid]])->whereIn('id', $old_sub_id_arr)->update(['create_at' => time(), 'create_status' => 2]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            SnCode::rollBackSnCode('PSO_');
            return response()->json(['code' => '001', 'msg' => '采购订单生成进货单失败' . $e->getMessage()]);
        }

        /***
         *  进货单
         *
         *
        */
//        if($info->is_from_sale!=2){
//            $Chanjet_param = [
//                "dto"=>[
//                    "ExternalCode"=>$maindata['order_sn_code'],
//                    "VoucherDate"=>date('Y-m-d'),
//                    "BusinessType" => [
//                        "Code" =>"01", //普通采购
//                    ],
//                    "Partner" => [
//                        "Code" => Custom::where('id',$maindata['custom_id'])->value('company_code')
//                    ],
//                    "Warehouse" => [
//                        "Code" => $Chanjet_VoucherDetails[0]['Warehouse']["Code"],
//                    ],
//                    "VoucherDetails" =>$Chanjet_VoucherDetails
//                ]
//            ];
//            if($this->mangerinfo['org_id']) {
//                ChanjetRequest::getInstance()->purchaseArrivalCreate($Chanjet_param,$this->mangerinfo['org_id']);
//            }
//
//        }
        return response()->json(['code' => '000', 'msg' => '采购订单生成进货单成功']);
    }


    /**
     * 生成预付单--只可单个订单生成预付单
     */
    public function createprepayorder(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $sub_order_id = is_array($request->sub_order_id) ? $request->sub_order_id : (is_array(json_decode($request->sub_order_id, true)) ? json_decode($request->sub_order_id, true) : []);
        $bankinfo = is_array($request->bankinfo) ? $request->bankinfo : (is_array(json_decode($request->bankinfo, true)) ? json_decode($request->bankinfo, true) : []);

        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = PurchaseOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        if ($info->pa_id <= 0) {
            return response()->json(['code' => '001', 'msg' => '协议信息不完整']);
        }

        if (count($sub_order_id) > 0) {
            $sub_order_count = PurchaseOrderSub::where([['order_id', $order_id], ['cpid', $cpid], ['pay_status', 1]])->whereIn('id', $sub_order_id)->count();
            if (count($sub_order_id) != $sub_order_count) {
                return response()->json(['code' => '001', 'msg' => '存在已付款订单，不可重复付款']);
            }
        } else {
            $sub_order_id = PurchaseOrderSub::where([['order_id', $order_id], ['cpid', $cpid], ['pay_status', 1]])->pluck('id');
        }




        //获取类型
        //理计初始平均重量为0，价格到时候也为0，生成金额为0的预付款单？
        //不同协议类型生成的单子不一致
        if ($info->settle_model == 3) { //后结算不可付款
            return response()->json(['code' => '001', 'msg' => '后结算不可付款']);
        }
        if (!(isset($bankinfo['bank']) && $bankinfo['bank'] != '') || !(isset($bankinfo['bank_number']) && $bankinfo['bank_number'] != '') || !(isset($bankinfo['bank_card_no']) && $bankinfo['bank_card_no'] != '') || !(isset($bankinfo['contacts']) && $bankinfo['contacts'] != '') || !(isset($bankinfo['phone_number']) && $bankinfo['phone_number'] != '')) {
            return response()->json(['code' => '001', 'msg' => '账户信息缺失']);
        }

        $pa_type = $info->pa_type; //1年度，2月度，3临时锁单
        $totalcount = PurchaseOrderSub::where([['order_id', $order_id], ['cpid', $cpid], ['pay_status', 1]])->whereIn('id', $sub_order_id)->sum('count');
        $pay_money = PurchaseOrderSub::where([['order_id', $order_id], ['cpid', $cpid], ['pay_status', 1]])->whereIn('id', $sub_order_id)->sum('total_money');
        $painfo = PurchaseAgreement::where([['cpid', $cpid], ['id', $info->pa_id]])->first();
        $payment_info = Custom::where([['cpid', $cpid], ['id', $info->custom_id]])->value('payment_info');
        $data = [
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            // 'pa_type' => $info->pa_type,
            'order_id' => $info->id,
            'sub_order' => json_encode($sub_order_id),
            'custom_id' => $info->custom_id,
            'pa_type' => $pa_type,
            'company_name' => $info->company_name,
            'count' => $totalcount,
            'pa_contract_no' => $info->pa_contract_no,
            'pa_settle_company_name' => $info->pa_settle_company_name,
            'bank' => $bankinfo['bank'],
            'bank_number' => $bankinfo['bank_number'],
            'bank_card_no' => $bankinfo['bank_card_no'],
            'contacts' => $bankinfo['contacts'],
            'phone_number' => $bankinfo['phone_number'],
            'pay_money' => $pay_money,
            'contract_filepath' => $painfo->contract_filepath,
            'contract_filename' => $painfo->contract_filename,
            'payment_info' => $payment_info,
            'remark' => $request->remark ?? '',
            'create_at' => time(),
            'update_at' => time(),
        ];

        if ($pa_type == 3 || $pa_type == 4) { //临时锁单需要增加字段
            $data['archive_material'] = strval($request->archive_material);
            $data['archive_spec'] = strval($request->archive_spec);
            $data['price'] = intval($request->price);
            $data['pre_pay_money'] = intval($request->pre_pay_money);
            $data['collect_money'] = intval($request->collect_money);
            $data['collect_bank'] = strval($request->collect_bank);
            $data['collect_info'] = strval($request->collect_info);
            $data['check_account_mobile'] = strval($request->check_account_mobile);
        }
        DB::beginTransaction();
        try {
            PurchasePrePayOrder::create($data);
            PurchaseOrderSub::where([['order_id', $order_id], ['cpid', $cpid], ['pay_status', 1]])->whereIn('id', $sub_order_id)->update(['pay_status' => 2, 'pay_at' => time()]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '采购订单付款失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '采购订单付款成功']);
    }


    /**
     * 生成预付单--只可单个订单生成预付单且不能拆单
     */
    public function createprepayorderwithoutsub(Request $request)
    {
        $order_id = $request->order_id ?? 0;

        $bankinfo = is_array($request->bankinfo) ? $request->bankinfo : (is_array(json_decode($request->bankinfo, true)) ? json_decode($request->bankinfo, true) : []);

        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = PurchaseOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        if ($info->pa_id <= 0) {
            return response()->json(['code' => '001', 'msg' => '协议信息不完整']);
        }
        $pay_money = intval($request->pay_money);

        if ($pay_money <= 0) {
            return response()->json(['code' => '001', 'msg' => '付款金额不能小于0']);
        }

        //点价锁价模式可以多次生成预付单

        // if ($info->pay_status != 1) {
        //     return response()->json(['code' => '001', 'msg' => '已付款无法重复付款']);
        // }

        //获取类型
        //理计初始平均重量为0，价格到时候也为0，生成金额为0的预付款单？
        //不同协议类型生成的单子不一致
        //后结算也可以付款
        // if ($info->settle_model == 3) { //后结算不可付款
        //     return response()->json(['code' => '001', 'msg' => '后结算不可付款']);
        // }
        if (!(isset($bankinfo['bank']) && $bankinfo['bank'] != '') || !(isset($bankinfo['bank_number']) && $bankinfo['bank_number'] != '') || !(isset($bankinfo['bank_card_no']) && $bankinfo['bank_card_no'] != '') || !(isset($bankinfo['contacts']) && $bankinfo['contacts'] != '') || !(isset($bankinfo['phone_number']) && $bankinfo['phone_number'] != '')) {
            return response()->json(['code' => '001', 'msg' => '账户信息缺失']);
        }

        $pa_type = $info->pa_type; //1年度，2月度，3临时锁单
        $totalcount = PurchaseOrderSub::where([['order_id', $order_id], ['cpid', $cpid]])->sum('count');
        //多次付款手动输入付款金额
        // $pay_money = PurchaseOrderSub::where([['order_id', $order_id], ['cpid', $cpid]])->sum('total_money');

        $painfo = PurchaseAgreement::where([['cpid', $cpid], ['id', $info->pa_id]])->first();
        $payment_info = Custom::where([['cpid', $cpid], ['id', $info->custom_id]])->value('payment_info');
        $data = [
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            // 'pa_type' => $info->pa_type,
            'order_id' => $info->id,
            'sub_order' => json_encode([]),
            'custom_id' => $info->custom_id,
            'pa_type' => $pa_type,
            'company_name' => $info->company_name,
            'count' => $totalcount,
            'pa_contract_no' => $info->pa_contract_no,
            'pa_settle_company_name' => $info->pa_settle_company_name,
            'bank' => $bankinfo['bank'],
            'bank_number' => $bankinfo['bank_number'],
            'bank_card_no' => $bankinfo['bank_card_no'],
            'contacts' => $bankinfo['contacts'],
            'phone_number' => $bankinfo['phone_number'],
            'pay_money' => $pay_money,
            'contract_filepath' => $painfo->contract_filepath,
            'contract_filename' => $painfo->contract_filename,
            'payment_info' => $payment_info,
            'remark' => $request->remark ?? '',
            'create_at' => time(),
            'update_at' => time(),
        ];

        if ($pa_type == 3 || $pa_type == 4) {
            $data['archive_material'] = strval($request->archive_material);
            $data['archive_spec'] = strval($request->archive_spec);
            $data['price'] = intval($request->price);
            $data['pre_pay_money'] = intval($request->pre_pay_money);
            $data['collect_money'] = intval($request->collect_money);
            $data['collect_bank'] = strval($request->collect_bank);
            $data['collect_info'] = strval($request->collect_info);
            $data['check_account_mobile'] = strval($request->check_account_mobile);
        }
        DB::beginTransaction();
        try {
            PurchasePrePayOrder::create($data);
            PurchaseOrderSub::where([['order_id', $order_id], ['cpid', $cpid], ['pay_status', 1]])->update(['pay_status' => 2, 'pay_at' => time()]);
            PurchaseOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'pay_status' => 1])->update(['pay_status' => 2, 'pay_at' => time()]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '采购订单付款失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '采购订单付款成功']);
    }

    /**
     * 获取付款信息
     */
    public function getbankinfowithorder(Request $request)
    {
        $order_id = $request->order_id ?? 0;


        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = PurchaseOrder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        $bankinfo = Custom::where(['id' => $info->custom_id, 'category' => 2])->value('bank_info');
        $bankinfo = json_decode($bankinfo, true);

        $pay_money = PurchaseOrderSub::where([['order_id', $order_id], ['cpid', $cpid]])->sum('total_money');
        //数组排序


        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['bankinfo' => $bankinfo, 'pay_money' => $pay_money]]);
    }


    /**
     * 获取付款信息
     */
    //    public function getbankinfowithorderarr(Request $request)
    //    {
    //        $order_id_arr = $request->order_id_arr ?? [];
    //        $cpid = $this->mangerinfo['cpid'];
    //        $manger_id = $this->mangerinfo['id'];
    //        $order_id_arr = is_array($order_id_arr) ? $order_id_arr : (is_array(json_decode($order_id_arr, true)) ? json_decode($order_id_arr, true) : []);
    //
    //
    //        $orderlist = PurchaseOrder::where(['manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])
    //            ->whereIn('id', $order_id_arr)->get()->toArray();
    //        if (count($orderlist) <= 0 || count($orderlist) != count($order_id_arr)) {
    //            return response()->json(['code' => '001', 'msg' => '付款订单参数错误']);
    //        }
    //        $pay_money = 0;
    //        $bankinfo = null;
    //        $custom_id = 0;
    //        $settle_company_id = 0;
    //        $custominfo = null;
    //        $contract_no_arr = [];
    //        foreach ($orderlist as $val) {
    //            if ($val['pa_id'] <= 0) {
    //                return response()->json(['code' => '001', 'msg' => '订单未绑定合同']);
    //            }
    //
    //            if ($custom_id == 0) {
    //                $custom_id = $val['custom_id'];
    //            } else {
    //                if ($custom_id != $val['custom_id']) {
    //                    return response()->json(['code' => '001', 'msg' => '订单不属于同一个客户']);
    //                }
    //            }
    //
    //            $custominfo_val = Custom::where(['id' => $val['custom_id'], 'category' => 2])->first();
    //
    //            //取协议信息
    //            $aginfo = PurchaseAgreement::where([['id', $val['pa_id']], ['cpid', $this->mangerinfo['cpid']], ['manger_id', $this->mangerinfo['id']]])->first();
    //            if (!$custominfo) {
    //                $custominfo = $custominfo_val;
    //                $bankinfo = json_decode($custominfo_val->bank_info, true);
    //            }
    //            if ($settle_company_id == 0) {
    //                $settle_company_id = $aginfo->settle_company_id;
    //            } else {
    //                if ($settle_company_id != $aginfo->settle_company_id) {
    //                    return response()->json(['code' => '001', 'msg' => '订单不属于同一个结算公司']);
    //                }
    //            }
    //
    //
    //
    //            $settle_company_name = $val['pa_settle_company_name'];
    //
    //            $contract_no_arr[] = $aginfo->contract_no;
    //            $pay_money_val = PurchaseOrderSub::where([['order_id', $val['id']], ['cpid', $cpid]])->sum('total_money');
    //            $pay_money = mathfuncmoney('add', $pay_money, $pay_money_val);
    //        }
    //        //数组排序
    //        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['pa_settle_company_name' => $settle_company_name, 'pa_contract_list' => join(',', $contract_no_arr), 'custominfo' => $custominfo, 'bankinfo' => $bankinfo, 'pay_money' => $pay_money]]);
    //    }

    /**
     * 获取付款信息
     */
    public function getbankinfowithorderarr(Request $request)
    {
        try {
            $ValidateSub = new PurchasePurchaseOrder('getbankinfowithorderarr');

            if (!$ValidateSub->check($request->input())) { //初筛过滤
                return response()->json(['code' => '001', 'msg' => $ValidateSub->getError()]);
            }
            $order_id_arr = $request->input('order_id_arr', []);
            $pa_type =  $request->input('pa_type', 1);

            $cpid = $this->mangerinfo['cpid'];
            $manger_id = $this->mangerinfo['id'];

            if (empty($order_id_arr)) {
                return response()->json(['code' => '001', 'msg' => '订单ID列表不能为空']);
            }

            $orderlist = $this->fetchOrderList($manger_id, $cpid, $pa_type, $order_id_arr);

            if ($orderlist->isEmpty()) {
                return response()->json(['code' => '001', 'msg' => '付款订单参数错误']);
            }

            $this->validateOrderConsistency($orderlist);

            $orderlist = $orderlist->toArray();

            $custominfo_list = $this->fetchCustomInfoList($orderlist);
            $aginfo_list = $this->fetchAgreementInfoList($orderlist);
            $order_sub_data = $this->fetchOrderSubData($orderlist, $cpid);

            $retdata = $this->buildResponseData($orderlist, $custominfo_list, $aginfo_list, $order_sub_data, $pa_type);

            return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $retdata]);
        } catch (\Exception $e) {
            return response()->json(['code' => '001', 'msg' => '系统异常: ' . $e->getMessage()]);
        }
    }

    private function fetchOrderList($manger_id, $cpid, $pa_type, $order_id_arr)
    {
        return PurchaseOrder::where(['manger_id' => $manger_id, 'cpid' => $cpid, 'pa_type' => $pa_type, 'is_del' => 1])
            ->whereIn('id', $order_id_arr)
            ->with(['custom', 'purchaseagreement'])
            ->get();
    }

    /**
     * 验证订单列表中所有订单的客户一致性
     *
     * 此方法的目的是确保给定的订单列表属于同一个客户
     * 它通过比较每个订单的pa_type和custom_id与列表中第一个订单的相应值来实现
     * 如果任何订单的pa_type或custom_id不匹配，将抛出异常
     *
     * @param \Illuminate\Database\Eloquent\Collection $orderlist 订单列表
     *
     * @throws \Exception 如果订单列表中的订单不属于同一个客户
     */
    private function validateOrderConsistency($orderlist)
    {
        // 获取订单列表中的第一个订单
        $firstOrder = $orderlist->first();

        // 初始化基准的pa_type和custom_id
        $basePaType = $firstOrder->pa_type;
        $baseCustomId = $firstOrder->custom_id;

        // 检查所有订单的pa_type和custom_id是否与基准值匹配
        $allMatch = $orderlist->every(function ($order) use ($basePaType, $baseCustomId) {
            return $order->pa_type === $basePaType && $order->custom_id === $baseCustomId;
        });

        // 如果不是所有订单都匹配，抛出异常
        if (!$allMatch) {
            throw new \Exception('订单不属于同一个客户');
        }
    }

    private function fetchCustomInfoList($orderlist)
    {
        return collect($orderlist)->mapWithKeys(function ($order) {
            return [$order['custom_id'] => $order['custom']];
        });
    }

    private function fetchAgreementInfoList($orderlist)
    {
        return collect($orderlist)->mapWithKeys(function ($order) {
            return [$order['pa_id'] => $order['purchaseagreement']];
        });
    }

    private function fetchOrderSubData($orderlist, $cpid)
    {
        return PurchaseOrderSub::whereIn('order_id', array_column($orderlist, 'id'))
            ->where('cpid', $cpid)
            ->select('order_id', DB::raw('SUM(total_money) as total_money'))
            ->groupBy('order_id')
            ->get()
            ->keyBy('order_id');
    }

    private function buildResponseData($orderlist, $custominfo_list, $aginfo_list, $order_sub_data, $pa_type)
    {
        $bankinfo = null;
        $payment_info = null;
        $settle_company_id = 0;
        $custominfo = null;
        $contract_no_arr = [];
        $retorderlist = [];
        $company_name = '';
        $settle_model = 0;

        foreach ($orderlist as $val) {
            if ($val['pa_id'] <= 0) {
                throw new \Exception('订单未绑定合同');
            }

            $custominfo_val = $custominfo_list->get($val['custom_id']);

            $aginfo = $aginfo_list->get($val['pa_id']);
            if (!$custominfo) {
                $custominfo = $custominfo_val;
                //                var_dump($custominfo);
                $bankinfo = json_decode($custominfo_val['bank_info'], true);
                $payment_info = json_decode($custominfo_val['payment_info'], true);
            }
            if ($settle_company_id == 0) {
                $settle_company_id = $aginfo['settle_company_id'];
            } else {
                if ($settle_company_id != $aginfo['settle_company_id']) {
                    throw new \Exception('订单不属于同一个结算公司');
                }
            }


            if ($settle_model == 0) {
                $settle_model = $val['settle_model'];
            } else {
                if ($settle_model != $val['settle_model']) {
                    throw new \Exception('订单不属于同一种结算方式');
                }
            }

            //            $settle_company_name = $val['pa_settle_company_name'];
            $company_name = $val['company_name'];

            $contract_no_arr[] = $aginfo['contract_no'];
            $pay_money_val = $order_sub_data->get($val['id'])->total_money ?? 0;
            $retorderlist[] = [
                //                'pa_sn_code' => $val['pa_sn_code'],
                'id' => $val['id'],
                'order_sn_code' => $val['order_sn_code'],
                'order_date' => $val['order_date'],
                'pay_money' => $pay_money_val,
            ];
        }




        return [
            'pa_type' => $pa_type,
            'company_name' => $company_name,
            'pa_contract_list' => join(',', $contract_no_arr),
            'custominfo' => $custominfo,
            'bankinfo' => $bankinfo,
            'payment_info' => $payment_info,
            'orderlist' => $retorderlist,
            'settle_model' => $settle_model,
            'pay_bank_by_settle_company_id'=>SettleCompany::where(['id'=>$settle_company_id])->value('settle_company_name')
        ];
    }


    /**
     * 生成预付单--只可单个订单生成预付单且不能拆单--未完成
     */
    //    public function createprepayorderbyorderarr(Request $request)
    //    {
    //
    //        $order_id_arr = $request->order_id_arr ?? [];
    //        $cpid = $this->mangerinfo['cpid'];
    //        $manger_id = $this->mangerinfo['id'];
    //        $order_id_arr = is_array($order_id_arr) ? $order_id_arr : (is_array(json_decode($order_id_arr, true)) ? json_decode($order_id_arr, true) : []);
    //
    //
    //        $bankinfo = is_array($request->bankinfo) ? $request->bankinfo : (is_array(json_decode($request->bankinfo, true)) ? json_decode($request->bankinfo, true) : []);
    //
    //        $cpid = $this->mangerinfo['cpid'];
    //        $manger_id = $this->mangerinfo['id'];
    //
    //        $orderlist = PurchaseOrder::where(['manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])
    //            ->whereIn('id', $order_id_arr)->get()->toArray();
    //
    //        if (count($orderlist) <= 0 || count($orderlist) != count($order_id_arr)) {
    //            return response()->json(['code' => '001', 'msg' => '付款订单参数错误']);
    //        }
    //        $pay_money = intval($request->pay_money);
    //
    //        if ($pay_money <= 0) {
    //            return response()->json(['code' => '001', 'msg' => '付款金额不能小于0']);
    //        }
    //        if (!(isset($bankinfo['bank']) && $bankinfo['bank'] != '') || !(isset($bankinfo['bank_number']) && $bankinfo['bank_number'] != '') || !(isset($bankinfo['bank_card_no']) && $bankinfo['bank_card_no'] != '') || !(isset($bankinfo['contacts']) && $bankinfo['contacts'] != '') || !(isset($bankinfo['phone_number']) && $bankinfo['phone_number'] != '')) {
    //            return response()->json(['code' => '001', 'msg' => '账户信息缺失']);
    //        }
    //
    //        $settle_type_info = SettleType::where([['id', intval($request->settle_type)], ['cpid', $cpid], ['status', 1]])->first();
    //
    //        if (!$settle_type_info) {
    //            return response()->json(['code' => '001', 'msg' => '无效结算方式']);
    //        }
    //
    //        $totalcount = PurchaseOrderSub::where([['cpid', $cpid]])->whereIn('order_id', $order_id_arr)->sum('count');
    //        $pay_sn_code = SnCode::getSnCode('PPO_');
    //        $data = [
    //            'cpid' => $cpid,
    //            'manger_id' => $manger_id,
    //            'order_ids' => join(',', $order_id_arr),
    //            'pay_sn_code' => $pay_sn_code,
    //            'pay_order_date' => time(),
    //            'custom_id' => $orderlist[0]['custom_id'],
    //            'company_name' => $orderlist[0]['company_name'],
    //            'product_channel' => strval($request->product_channel),
    //            'delivery_cycle' => strval($request->delivery_cycle),
    //            'breed_name' => strval($request->breed_name),
    //            'count' => $totalcount,
    //            'pa_contract_list' => strval($request->pa_contract_list),
    //            'pa_settle_company_id' => strval($orderlist[0]['pa_settle_company_id']),
    //            'pa_settle_company_name' => strval($orderlist[0]['pa_settle_company_name']),
    //            'settle_type' => $settle_type_info->id,
    //            'settle_type_name' => $settle_type_info->type_name,
    //            'bank' => $bankinfo['bank'],
    //            'bank_number' => $bankinfo['bank_number'],
    //            'bank_card_no' => $bankinfo['bank_card_no'],
    //            'contacts' => $bankinfo['contacts'],
    //            'phone_number' => $bankinfo['phone_number'],
    //            'pay_money' => $pay_money,
    //            'contract_info' => strval($request->contract_info),
    //            'setpay_info' => strval($request->setpay_info),
    //            'urgent_remark' => strval($request->urgent_remark),
    //            'is_screenshot' => strval($request->is_screenshot),
    //            'remark' => $request->remark ?? '',
    //            'create_at' => time(),
    //            'update_at' => time(),
    //        ];
    //        $datawp = [
    //            'cpid' => $cpid,
    //            'manger_id' => $manger_id,
    //            'type' => 2,
    //            'pay_money' => $pay_money,
    //            'pay_sn_code' => $pay_sn_code,
    //            'create_at' => time(),
    //            'update_at' => time(),
    //        ];
    //        DB::beginTransaction();
    //        try {
    //            PurchasePayOrderNew::create($data);
    //            PurchaseOrderSub::where([['cpid', $cpid], ['pay_status', 1]])->whereIn('order_id', $order_id_arr)->update(['pay_status' => 2, 'pay_at' => time()]);
    //            PurchaseOrder::where(['manger_id' => $manger_id, 'cpid' => $cpid, 'pay_status' => 1])->whereIn('id', $order_id_arr)->update(['pay_status' => 2, 'pay_at' => time()]);
    //
    //            PurchaseWarehousingOrderwithpay::create($datawp);
    //
    //
    //            //提交审批
    //
    //            //提交审批成功则审批状态改为待审核
    //
    //
    //            DB::commit();
    //        } catch (\Exception $e) {
    //
    //            SnCode::rollBackSnCode('PPO_');
    //            DB::rollBack();
    //            Log::info($e->getMessage());
    //            return response()->json(['code' => '001', 'msg' => '采购订单付款失败' . $e->getMessage()]);
    //        }
    //
    //        return response()->json(['code' => '000', 'msg' => '采购订单付款成功']);
    //    }

    /**
     * 生成预付单--只可单个订单生成预付单且不能拆单--未完成
     */
    public function createprepayorderbyorderarr(Request $request)
    {
        $order_id_arr = $request->order_id_arr ?? [];
        $order_list = $request->orderlist ?? [];
        $order_id_arr = is_array($order_id_arr) ? $order_id_arr : (is_array(json_decode($order_id_arr, true)) ? json_decode($order_id_arr, true) : []);

        $order_list = is_array($order_list) ? $order_list : (is_array(json_decode($order_list, true)) ? json_decode($order_list, true) : []);

        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];

        $orderlist = PurchaseOrder::where(['manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])
            ->whereIn('id', $order_id_arr)->get()->toArray();

        if (empty($orderlist) || empty($order_list)) {
            return response()->json(['code' => '001', 'msg' => '付款订单参数错误']);
        }
        //        $this->validateOrderConsistency($orderlist);
        //        dd(1);

        $pay_money = array_sum(array_column($order_list, 'pay_money'));
        $totalcount = PurchaseOrderSub::where([['cpid', $cpid]])->whereIn('order_id', $order_id_arr)->sum('count');
        $pay_sn_code = SnCode::getSnCode('PPO_');
        $data = [
            'cpid' => $cpid,
            'manger_id' => $manger_id,
            'order_ids' => join(',', $order_id_arr),
            'pay_sn_code' => $pay_sn_code,
            'pay_order_date' => time(),
            'pa_type' => strval($request->pa_type),
            'custom_id' => $orderlist[0]['custom_id'],
            'company_name' => $orderlist[0]['company_name'],
            'pa_settle_company_id' => strval($orderlist[0]['pa_settle_company_id']),
            'pa_settle_company_name' => strval($orderlist[0]['pa_settle_company_name']),
            'settle_model' => intval($request->settle_model),
            'pa_contract_list' => strval($request->pa_contract_list),
            'delivery_cycle' => strval($request->delivery_cycle),
            'payment_type' => intval($request->payment_type),
            'steel_mill' => strval($request->steel_mill),
            'material_specifications' => strval($request->material_specifications),
            'count' => $totalcount,
            'weight' => mathfuncweight('mul',floatval($request->weight),1000,1),
            'unit_price' => mathfuncmoney('mul',floatval($request->unit_price),100),
            'payment_status' => intval($request->payment_status),
            'pay_bank' => strval($request->pay_bank),
            'bank' => strval($request->bank),
            'bank_number' => strval($request->bank_number),
            'bank_card_no' => strval($request->bank_card_no),
            'contacts' => strval($request->contacts),
            'pay_money' => $pay_money, //求和
            'urgent_remark' => strval($request->urgent_remark),
            'reconciliation_phone_number' => strval($request->reconciliation_phone_number),
            'contract_info' => strval($request->contract_info),
            'approve_id1' => strval($request->approve_id1),
            'approve_id2' => strval($request->approve_id2),
            'order_list' => json_encode($order_list),
            'remark' => strval($request->remark) ?? '',
            'create_at' => time(),
            'update_at' => time(),

        ];
        //        $datawp = [
        //            'cpid' => $cpid,
        //            'manger_id' => $manger_id,
        //            'type' => 2,
        //            'pay_money' => $pay_money,
        //            'pay_sn_code' => $pay_sn_code,
        //            'create_at' => time(),
        //            'update_at' => time(),
        //        ];

        $approval_firstStep = DB::table('approval_steps')
            ->where('flow_id', '=', 1)
            ->orderBy('step_order', 'asc')
            ->first();


        DB::beginTransaction();
        try {
            $PayOrder = PurchasePayOrderApprove::create($data);

            DB::table('order_approvals')
                ->insert([
                    'order_id' => $PayOrder->id,
                    'type' => 'purchase_pay_order_approve',
                    'current_step_id' => $approval_firstStep->id,
                ]);

            DB::table('approval_histories')
                ->insert([
                    'order_id' => $PayOrder->id,
                    'type' => 'purchase_pay_order_approve',
                    'step_id' => $approval_firstStep->id,
                    'approver_id' => $manger_id,
                    'status' => 'pending',
                ]);
            //审批通过后添加数据
            //            PurchaseWarehousingOrderwithpay::create($datawp);

            DB::commit();
        } catch (\Exception $e) {

            SnCode::rollBackSnCode('PPO_');
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '采购订单付款失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '采购订单付款成功']);
    }
}
